package com.iflytek.uoamp.agent.core.sender.monitorsender;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.iflytek.uoamp.agent.core.AgentCoreMain;
import com.iflytek.uoamp.agent.core.agentclient.sync.SyncWrite;
import com.iflytek.uoamp.agent.core.conf.AgentCoreConfig;
import com.iflytek.uoamp.agent.core.sender.monitorsender.monitorinterface.Iface;
import com.iflytek.uoamp.agent.core.sender.monitorsender.responseObj.*;
import com.iflytek.uoamp.agent.core.sender.obj.MsgType;
import com.iflytek.uoamp.agent.core.sender.obj.RequestData;
import com.iflytek.uoamp.agent.core.sender.obj.ResponseData;
import com.iflytek.uoamp.agent.core.sender.obj.SysType;

import org.apache.log4j.Logger;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
 * @ClassName: MethodClient
 * @Description: 发送客户端请求
 * @author qinanyuan
 * @date 2017年3月22日 下午9:08:47
 */
public class MonitorSendMethod implements Iface {
	
	private final Integer REQUEST_TIME_OUT = AgentCoreConfig.getInstance().getConnectOutTime();
	
	private SyncWrite s = new SyncWrite();

    public Status converResult(String result){
        Status status = null;
        if(result.equals("OK")){
            return Status.OK;
        }else if(result.equals("FAILED")){
            return Status.FAILED;
        }else if(result.equals("ERROR")){
            return Status.ERROR;
        }else if(result.equals("UNKNOWN")){
            return Status.UNKNOWN;
        }
        return status;
    }
    
	@Override
	public Status addServices(List<Program> programs) {
        Status status = null;
        try{
            RequestData request = new RequestData();
            request.setSysType(SysType.MONITOR);
            request.setMsgType(MsgType.REQUEST);
            request.setRequestInfo(JSON.toJSONString(programs));
            request.setMethod("addServices");
            Logger.getRootLogger().info("addServices请求数据："+ JSON.toJSON(request));
            ResponseData response = s.writeAndSync(AgentCoreMain.getAgentClient().getFuture().channel(), request, REQUEST_TIME_OUT);
            Logger.getRootLogger().info("addServices调用结果："+ JSON.toJSON(response));
            status = converResult(response.getResponseInfo());
        }catch (Exception e){
        	Logger.getRootLogger().error("addServices fail! The Exception is ："+ e);
        }
		return status;
	}

	@Override
	public List<BMonitorItem> initMonitorItem(ItemType itemType) {
        List<BMonitorItem> result = new ArrayList<BMonitorItem>();
        try{
            RequestData request = new RequestData();
            request.setSysType(SysType.MONITOR);
            request.setMsgType(MsgType.REQUEST);
            request.setRequestInfo(JSON.toJSONString(itemType));
            request.setMethod("initMonitorItem");
            Logger.getRootLogger().info("initMonitorItem请求数据："+ JSON.toJSON(request));
            ResponseData response = s.writeAndSync(AgentCoreMain.getAgentClient().getFuture().channel(), request, REQUEST_TIME_OUT);
            Logger.getRootLogger().info("initMonitorItem调用结果："+ JSON.toJSON(response));
            JSONArray JSONArray = JSON.parseArray(response.getResponseInfo());
            for (Object object:JSONArray) {
                BMonitorItem Item = new BMonitorItem();
                Item.setBody(((JSONObject)object).get("body").toString());
                result.add(Item);

            }
        }catch (Exception e){
        	Logger.getRootLogger().error("initMonitorItem fail! The Exception is ："+ e);
        }
        return result;
	}

	@Override
	public List<BMonitorItem> getMonitorItem(ItemType itemType, List<String> namelist) {
        Map<String , Object> requsetMap = new HashMap<String, Object>();
        requsetMap.put("itemType" , itemType);
        requsetMap.put("namelist" , namelist);
        List<BMonitorItem> result = null;
        try{
            RequestData request = new RequestData();
            request.setSysType(SysType.MONITOR);
            request.setMsgType(MsgType.REQUEST);
            request.setRequestInfo(JSON.toJSONString(requsetMap));
            request.setMethod("getMonitorItem");
            Logger.getRootLogger().info("getMonitorItem请求数据："+ JSON.toJSON(request));
            ResponseData response = s.writeAndSync(AgentCoreMain.getAgentClient().getFuture().channel(), request, REQUEST_TIME_OUT);
            Logger.getRootLogger().info("getMonitorItem调用结果："+ JSON.toJSON(response));
            result = JSON.parseArray(response.getResponseInfo() , BMonitorItem.class);
        }catch (Exception e){
        	Logger.getRootLogger().error("getMonitorItem fail! The Exception is ："+ e);
        }
        return result;
	}

	@Override
	public BMonitorResponse send(BMonitorRequest req) {
        BMonitorResponse result = null;
        try{
            RequestData request = new RequestData();
            request.setSysType(SysType.MONITOR);
            request.setMsgType(MsgType.REQUEST);
            request.setRequestInfo(JSON.toJSONString(req));
            request.setMethod("send");
            Logger.getRootLogger().info("send请求数据："+ JSON.toJSON(request));
            ResponseData response = s.writeAndSync(AgentCoreMain.getAgentClient().getFuture().channel(), request, REQUEST_TIME_OUT);
            Logger.getRootLogger().info("send调用结果："+ JSON.toJSON(response));
            result = JSON.parseObject(response.getResponseInfo() , BMonitorResponse.class);
        }catch (Exception e){
        	Logger.getRootLogger().error("send fail! The Exception is ："+ e);
        }
        return result;
	}

	@Override
	public BMonitorResponse sendBatch(List<BMonitorRequest> reqs) {
        BMonitorResponse result = null;
        try{
            RequestData request = new RequestData();
            request.setSysType(SysType.MONITOR);
            request.setMsgType(MsgType.REQUEST);
            request.setRequestInfo(JSON.toJSONString(reqs));
            request.setMethod("sendBatch");
            Logger.getRootLogger().info("sendBatch请求数据："+ JSON.toJSON(request));
            ResponseData response = s.writeAndSync(AgentCoreMain.getAgentClient().getFuture().channel(), request, REQUEST_TIME_OUT);
            Logger.getRootLogger().info("sendBatch调用结果："+ JSON.toJSON(response));
            result = JSON.parseObject(response.getResponseInfo() , BMonitorResponse.class);
        }catch (Exception e){
        	Logger.getRootLogger().error("sendBatch fail! The Exception is ："+ e);
        }
        return result;
	}

	@Override
	public Status append(ThriftFlumeEvent event) {
        Status status = null;
        try{
            RequestData request = new RequestData();
            request.setSysType(SysType.MONITOR);
            request.setMsgType(MsgType.REQUEST);
            request.setRequestInfo(JSON.toJSONString(event));
            request.setMethod("append");
            Logger.getRootLogger().info("append请求数据："+ JSON.toJSON(request));
            ResponseData response = s.writeAndSync(AgentCoreMain.getAgentClient().getFuture().channel(), request, REQUEST_TIME_OUT);
            Logger.getRootLogger().info("append调用结果："+ JSON.toJSON(response));
            status = converResult(response.getResponseInfo());
        }catch (Exception e){
        	Logger.getRootLogger().error("append fail! The Exception is ："+ e);
        }

        return status;
	}

	@Override
	public Status appendBatch(List<ThriftFlumeEvent> events) {
        Status status = null;
        try{
            RequestData request = new RequestData();
            request.setSysType(SysType.MONITOR);
            request.setMsgType(MsgType.REQUEST);
            request.setRequestInfo(JSON.toJSONString(events));
            request.setMethod("appendBatch");
            Logger.getRootLogger().info("appendBatch请求数据："+ JSON.toJSON(request));
            ResponseData response = s.writeAndSync(AgentCoreMain.getAgentClient().getFuture().channel(), request, REQUEST_TIME_OUT);
            Logger.getRootLogger().info("appendBatch调用结果："+ JSON.toJSON(response));
            status = converResult(response.getResponseInfo());
        }catch (Exception e){
        	Logger.getRootLogger().error("appendBatch fail! The Exception is ："+ e);
        }

        return status;
	}

	@Override
	public Status ping(String ip) {
        Status status = null;
        try{
            RequestData request = new RequestData();
            request.setSysType(SysType.MONITOR);
            request.setMsgType(MsgType.PING);
            request.setRequestInfo(ip);
            request.setMethod("ping");
            Logger.getRootLogger().info("ping请求数据："+ JSON.toJSON(request));
            ResponseData response = s.writeAndSync(AgentCoreMain.getAgentClient().getFuture().channel(), request, REQUEST_TIME_OUT);
            Logger.getRootLogger().info("ping调用结果："+ JSON.toJSON(response));
            status = converResult(response.getResponseInfo());
        }catch (Exception e){
        	Logger.getRootLogger().error("ping fail! The Exception is ："+ e);
        }

		return status;
	}

	@Override
	public List<NewVersion> getAllConfig(RequestVersion ip) {
        List<NewVersion> result = null;
        try{
            RequestData request = new RequestData();
            request.setSysType(SysType.MONITOR);
            request.setMsgType(MsgType.REQUEST);
            request.setRequestInfo(JSON.toJSONString(ip));
            request.setMethod("getAllConfig");
            Logger.getRootLogger().info("getAllConfig请求数据："+ JSON.toJSON(request));
            ResponseData response = s.writeAndSync(AgentCoreMain.getAgentClient().getFuture().channel(), request, REQUEST_TIME_OUT);
            Logger.getRootLogger().info("getAllConfig调用结果："+ JSON.toJSON(response));
            result = JSON.parseArray(response.getResponseInfo() , NewVersion.class);
        }catch (Exception e){
        	Logger.getRootLogger().error("getAllConfig fail! The Exception is ："+ e);
        }
        return result;
	}

	@Override
	public Map<String, String> isUpdate(ClientVersion version) {
        Map<String, String> result = null;
        try{
            RequestData request = new RequestData();
            request.setSysType(SysType.MONITOR);
            request.setMsgType(MsgType.REQUEST);
            request.setRequestInfo(JSON.toJSONString(version));
            request.setMethod("isUpdate");
            Logger.getRootLogger().info("isUpdate请求数据："+ JSON.toJSON(request));
            ResponseData response = s.writeAndSync(AgentCoreMain.getAgentClient().getFuture().channel(), request, REQUEST_TIME_OUT);
            Logger.getRootLogger().info("isUpdate调用结果："+ JSON.toJSON(response));
            result = JSON.parseObject(response.getResponseInfo() , new TypeReference<Map<String, String>>(){});
        }catch (Exception e){
        	Logger.getRootLogger().error("isUpdate fail! The Exception is ："+ e);
        }
        return result;
	}

	@Override
	public boolean log(AgentLog logcontent) {
        boolean result = false;
        try{
            RequestData request = new RequestData();
            request.setSysType(SysType.MONITOR);
            request.setMsgType(MsgType.REQUEST);
            request.setRequestInfo(JSON.toJSONString(logcontent));
            request.setMethod("log");
            Logger.getRootLogger().info("log请求数据："+ JSON.toJSON(request));
            ResponseData response = s.writeAndSync(AgentCoreMain.getAgentClient().getFuture().channel(), request, REQUEST_TIME_OUT);
            Logger.getRootLogger().info("log调用结果："+ JSON.toJSON(response));
            if (response.getResponseInfo().equals("OK")){
            	result = true;
            }
        }catch (Exception e){
        	Logger.getRootLogger().error("AgentLog fail! The Exception is ："+ e);
        }
        return result;
	}

	@Override
	public AutoPluginFile downloadPlugin(String filename) {
        AutoPluginFile result = new AutoPluginFile();
        try{
            RequestData request = new RequestData();
            request.setSysType(SysType.MONITOR);
            request.setMsgType(MsgType.REQUEST);
            request.setRequestInfo(filename);
            request.setMethod("downloadPlugin");
            Logger.getRootLogger().info("downloadPlugin请求数据："+ JSON.toJSONString(request));
            ResponseData response = s.writeAndSync(AgentCoreMain.getAgentClient().getFuture().channel(), request, REQUEST_TIME_OUT);
            Logger.getRootLogger().info("downloadPlugin调用结果："+ JSON.toJSONString(response));
            result = JSON.parseObject(response.getResponseInfo() , AutoPluginFile.class);
//            JSONObject responseInfo = JSONObject.parseObject(response.getResponseInfo());
//            result.setFilebyte(responseInfo.get("filebyte").toString().getBytes());
//            result.setFilename(responseInfo.getString("filename"));
//            Logger.getRootLogger().info("downloadPlugin返回结果："+ JSON.toJSONString(result));
        }catch (Exception e){
        	Logger.getRootLogger().error("downloadPlugin fail! The Exception is ："+ e);
        }
        return result;
	}

	@Override
	public String uploadInformation(String info) {
        String result = null;
        try{
            RequestData request = new RequestData();
            request.setSysType(SysType.MONITOR);
            request.setMsgType(MsgType.REQUEST);
            request.setRequestInfo(info);
            request.setMethod("uploadInformation");
            Logger.getRootLogger().info("uploadInformation请求数据："+ JSON.toJSON(request));
            ResponseData response = s.writeAndSync(AgentCoreMain.getAgentClient().getFuture().channel(), request, REQUEST_TIME_OUT);
            Logger.getRootLogger().info("uploadInformation调用结果："+ JSON.toJSON(response));
            result = response.getResponseInfo();
        }catch (Exception e){
        	Logger.getRootLogger().error("uploadInformation fail! The Exception is ："+ e);
        }
        return result;
	}

	@Override
	public Map<String, String> getComponentList() {
        Map<String, String> result = null;
        try{
            RequestData request = new RequestData();
            request.setSysType(SysType.MONITOR);
            request.setMsgType(MsgType.REQUEST);
            request.setRequestInfo(JSON.toJSONString(""));
            request.setMethod("getComponentList");
            Logger.getRootLogger().info("getComponentList请求数据："+ JSON.toJSON(request));
            ResponseData response = s.writeAndSync(AgentCoreMain.getAgentClient().getFuture().channel(), request, REQUEST_TIME_OUT);
            Logger.getRootLogger().info("getComponentList调用结果："+ JSON.toJSON(response));
            result = JSON.parseObject(response.getResponseInfo() , new TypeReference<Map<String, String>>(){});
        }catch (Exception e){
        	Logger.getRootLogger().error("getComponentList fail! The Exception is ："+ e);
        }
        return result;
	}

	@Override
	public Map<String, String> getPluginFileList(String type) {
        Map<String, String> result = null;
        try{
            RequestData request = new RequestData();
            request.setSysType(SysType.MONITOR);
            request.setMsgType(MsgType.REQUEST);
            request.setRequestInfo(type);
            request.setMethod("getPluginFileList");
            Logger.getRootLogger().info("getPluginFileList请求数据："+ JSON.toJSON(request));
            ResponseData response = s.writeAndSync(AgentCoreMain.getAgentClient().getFuture().channel(), request, REQUEST_TIME_OUT);
            Logger.getRootLogger().info("getPluginFileList调用结果："+ JSON.toJSON(response));
            result = JSON.parseObject(response.getResponseInfo() , new TypeReference<Map<String, String>>(){});
        }catch (Exception e){
        	Logger.getRootLogger().error("getPluginFileList fail! The Exception is ："+ e);
        }
        return result;
	}

	@Override
	public Map<String, String> getAgentVersionInfo() {
        Map<String, String> result = null;
        try{
            RequestData request = new RequestData();
            request.setSysType(SysType.MONITOR);
            request.setMsgType(MsgType.REQUEST);
            request.setRequestInfo(JSON.toJSONString(""));
            request.setMethod("getAgentVersionInfo");
            Logger.getRootLogger().info("getAgentVersionInfo请求数据："+ JSON.toJSON(request));
            ResponseData response = s.writeAndSync(AgentCoreMain.getAgentClient().getFuture().channel(), request, REQUEST_TIME_OUT);
            Logger.getRootLogger().info("getAgentVersionInfo调用结果："+ JSON.toJSON(response));
            result = JSON.parseObject(response.getResponseInfo() , new TypeReference<Map<String, String>>(){});
        }catch (Exception e){
        	Logger.getRootLogger().error("getAgentVersionInfo fail! The Exception is ："+ e);
        }
        return result;
	}

	@Override
	public AutoPluginFile downloadAgentPackage() {
        AutoPluginFile result = new AutoPluginFile();
        try{
            RequestData request = new RequestData();
            request.setSysType(SysType.MONITOR);
            request.setMsgType(MsgType.REQUEST);
            request.setRequestInfo(JSON.toJSONString(""));
            request.setMethod("downloadAgentPackage");
            Logger.getRootLogger().info("downloadAgentPackage请求数据："+ JSON.toJSON(request));
            ResponseData response = s.writeAndSync(AgentCoreMain.getAgentClient().getFuture().channel(), request, REQUEST_TIME_OUT);
            Logger.getRootLogger().info("downloadAgentPackage调用结果："+ JSON.toJSON(response));
//            JSONObject responseInfo = JSONObject.parseObject(response.getResponseInfo());
//            result.setFilebyte(responseInfo.get("filebyte").toString().getBytes());
//            result.setFilename(responseInfo.getString("filename"));
            result = JSON.parseObject(response.getResponseInfo() , AutoPluginFile.class);
        }catch (Exception e){
        	Logger.getRootLogger().error("downloadAgentPackage fail! The Exception is ："+ e);
        }
        return result;
	}

	@Override
	public Status proxyPing(String ip) {
        Status status = null;
        try{
            RequestData request = new RequestData();
            request.setSysType(SysType.MONITOR);
            request.setMsgType(MsgType.REQUEST);
            request.setRequestInfo(ip);
            request.setMethod("proxyPing");
            Logger.getRootLogger().info("proxyPing请求数据："+ JSON.toJSON(request));
            ResponseData response = s.writeAndSync(AgentCoreMain.getAgentClient().getFuture().channel(), request, REQUEST_TIME_OUT);
            Logger.getRootLogger().info("proxyPing调用结果："+ JSON.toJSON(response));
            status = converResult(response.getResponseInfo());
        }catch (Exception e){
        	Logger.getRootLogger().error("proxyPing fail! The Exception is ："+ e);
        }

        return status;
	}
}
